package com.example.service.impl;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.result.Result;
import com.example.common.result.YiFeiException;
import com.example.entity.dto.*;
import com.example.entity.hz.IHead;
import com.example.entity.hz.MOCTA;
import com.example.entity.hz.SFCTA;
import com.example.entity.mysql.Productprocessresource;
import com.example.entity.mysql.Workresource;
import com.example.entity.vo.*;
import com.example.entity.yifei.*;
import com.example.enums.MOCStatusEnum;
import com.example.exception.CustomException;
import com.example.mapper.*;
import com.example.mapper.pc.ResourceMapper;
import com.example.mapper.pc.WorkresourceMapper;
import com.example.service.*;
import com.example.service.pc.ProductprocessresourceService;
import com.example.untils.BeanUtils;
import com.example.untils.SecurityUtils;
import com.example.untils.TimeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: LiangPanDeng
 * @Date: 2023/12/15/15:14
 * @Description:    派工/报工 service 接口实现类
 */
@Slf4j
@Service
public class SFCTEServiceImpl extends ServiceImpl<SFCTEMapper, SFCTE> implements SFCTEService {

    private final String url = "http://192.168.1.168:8080/img/";
    @Resource
    private SfctaMapper sfctaMapper;
    @Resource
    private SFCTEMapper sfcteMapper;
    @Autowired
    private ZnxService znxService;
    @Resource
    private MoctaMapper moctaMapper;
    @Resource
    private CmsmeMapper cmsmeMapper;
    @Resource
    private SFCTDMapper sfctdMapper;
    @Resource
    private InvmbMapper invmbMapper;
    @Resource
    private QmsmgMapper qmsmgMapper;
    @Resource
    private IHeadMapper iHeadMapper;
    @Resource
    private CmsmvMapper cmsmvMapper;
    @Resource
    private CmsmdMapper cmsmdMapper;
    @Resource
    private CommonMapper commonMapper;
    @Resource
    private ResourceMapper resourceMapper;
    @Resource
    private MoctyMapper moctyMapper;
    @Resource
    private ResourceusehisMapper resourceusehisMapper;
    @Resource
    private ResourceusehisService resourceusehisService;
    @Resource
    private WorkresourceMapper workresourceMapper;
    @Resource
    private MaintainplanMapper maintainplanMapper;
    @Resource
    private MaintainplanruleMapper maintainplanruleMapper;
    @Resource
    private ResourceMaintainplanMapper resourceMaintainplanMapper;
    @Resource
    private MaintainplanitemMapper maintainplanitemMapper;
    @Autowired
    private EqtteService eqtteService;
    @Autowired
    private EqtteMapper eqtteMapper;
    @Autowired
    private EqttfService eqttfService;
    @Autowired
    private EqttfMapper eqttfMapper;
    @Autowired
    private ProductprocessresourceService pprService;
    @Autowired
    private SfcteresourceMapper sfcteresourceMapper;
    @Autowired
    private SfcteresourcehisMapper sfcteresourcehisMapper;
//    @Resource
//    private Maintainplangroup

    @Override
    @Transactional
    public Result saveSfcTdAndSfcTeBg(List<SfcTeListVo> sfcTeListVoList) {

        String nowTime = new SimpleDateFormat("yyyyMMddHHmmss").
                format(new Date()).replaceAll("-", "").
                replaceAll(":", "").replaceAll(" ", "");
        if (!sfcTeListVoList.isEmpty()){
            for (SfcTeListVo arr : sfcTeListVoList) {
                if(com.example.untils.StringUtils.isEmpty(arr.getTe006())) {
                    throw new CustomException("500", "工单单别不能为空!");
                }
                if(com.example.untils.StringUtils.isEmpty(arr.getTe007())) {
                    throw new CustomException("500", "工单单号不能为空!");
                }
                if(com.example.untils.StringUtils.isEmpty(arr.getTe008())) {
                    throw new CustomException("500", "工单工序不能为空!");
                }
                if(arr.getTe011() == null || arr.getUdf51() == null || arr.getUdf52() == null || arr.getUdf53() == null) {
                    throw new CustomException("500", "合格数量, 工废数量, 料废数量, 不良数量不能为空!");
                }
                if(arr.getTe011().add(arr.getUdf51()).add(arr.getUdf52()).add(arr.getUdf53()).compareTo(new BigDecimal(0)) <= 0) {
                    throw new CustomException("500", "合格数量 + 工废数量 + 料废数量 + 不良数量需大于0!");
                }
                //查询上一道数据的已报工数量。
//                    SFCTA sfcta = sfctaMapper.getLastDishNum(arr.getTe006(), arr.getTe007(), arr.getTe008());
//                    if (sfcta != null) {
//                        Double num = sfcta.getTA011().doubleValue() + sfcta.getUDF51().doubleValue() + sfcta.getUDF52().doubleValue() + sfcta.getUDF53().doubleValue();
//                        if (num > arr.getTe011().doubleValue() + arr.getUdf51().doubleValue() + arr.getUdf52().doubleValue() + arr.getUdf53().doubleValue()) {
//                            return Result.fail("报工数量大于上道工序报工数量，不予报工");
//                        }
//                    }

                // 查询同一张派工单中，上一道工序的已报工数量。
                SFCTA sfcta = sfctaMapper.getLastDishNum(arr.getTe006(), arr.getTe007(), arr.getTe008());
                // 查询派工单
                SFCTE d420 = sfcteMapper.selectOne(new LambdaQueryWrapper<SFCTE>().eq(SFCTE::getTE001, arr.getTe001()).eq(SFCTE::getTE002, arr.getTe002()).eq(SFCTE::getTE003, arr.getTe003()));
                if(d420 == null) {
                    throw new CustomException("500", "派工单: " + arr.getTe001() + "-" + arr.getTe002() + "-" + arr.getTe003() + "不存在");
                }
                // 本工序已报数量
                BigDecimal bgNums = sfcteMapper.getAlreadyBG(arr.getTe001(), arr.getTe002(), arr.getTe003());
                if(sfcta != null) {   // 如果有上工序，则判断
                    BigDecimal sgxHgNums = new BigDecimal(0D);
                    SFCTE sfcte = sfcteMapper.selectOne(new LambdaQueryWrapper<SFCTE>().eq(SFCTE::getTE001, arr.getTe001()).eq(SFCTE::getTE002, arr.getTe002())
                            .eq(SFCTE::getTE006, arr.getTe006()).eq(SFCTE::getTE007, arr.getTe007()).eq(SFCTE::getTE008, sfcta.getTA003()));
                    if(sfcte != null) {
                        // 上工序合格数量
                        sgxHgNums = sfcteMapper.getBGhgNums(sfcte.getTE001(), sfcte.getTE002(), sfcte.getTE003());
                    }
                    if(bgNums.add(arr.getTe011()).add(arr.getUdf51()).add(arr.getUdf52()).add(arr.getUdf53()).compareTo(sgxHgNums) > 0) {
                        throw new CustomException("500", "报工单, 合格数量:" + arr.getTe011() + " + 工废数量:" + arr.getUdf51() + " + 料废数量:" + arr.getUdf52() + " + 不良数量:" + arr.getUdf53() + " 大于 " +
                                "剩余可报工数量(上道工序的合格数量 - 已报工数量): " + sgxHgNums.subtract(bgNums) + " !!");
                    }
                }
//                    List<SFCTE> sfcteList = this.sfcteMapper.selectList(new LambdaQueryWrapper<SFCTE>().eq(SFCTE::getTE001, arr.getTe001()).eq(SFCTE::getTE002, arr.getTe002()));
//                    if (!sfcteList.isEmpty()) {
                SFCTD sfctd1 = new SFCTD();
                LocalDateTime currentTime = LocalDateTime.now();
                DateTimeFormatter yyyyMM = DateTimeFormatter.ofPattern("yyyyMMdd");
                sfctd1.setTD001("D410");
                Long dh = commonMapper.getDH2("SFCTD", "TD002", "TD001", "D410");
                if (dh == null) {
                    dh = Long.parseLong(currentTime.format(yyyyMM)+"001");
                } else {
                    dh++;
                }
                sfctd1.setTD002(""+dh);
                sfctd1.setTD003(nowTime.substring(0, 8));
                sfctd1.setTD004(arr.getTd004());
                sfctd1.setCREATE_DATE(nowTime);
                this.sfctdMapper.save(sfctd1);
                SFCTE sfcte = new SFCTE();
                sfcte.setTE001(sfctd1.getTD001());
                sfcte.setTE002(sfctd1.getTD002());
                sfcte.setTE003(SerialNumberSfcte(sfctd1.getTD001(), sfctd1.getTD002()));
                sfcte.setTE008(arr.getTe008());
                sfcte.setUDF09(arr.getTe001());    //  派工单单别
                sfcte.setUDF10(arr.getTe002());   //  派工单单号
                sfcte.setUDF11(arr.getTe003());   //  派工单序号
                sfcte.setUDF07(arr.getUdf07());
                sfcte.setTE004(arr.getTe004());
                sfcte.setTE009(arr.getTe009());

                //派工回写，工单工艺回写
                QueryWrapper<SFCTA> wrapper = new QueryWrapper<>();
                wrapper.eq("TA001", arr.getTe006())
                        .eq("TA002", arr.getTe007())
                        .eq("TA003", arr.getTe008());
                SFCTA sfcta1 = sfctaMapper.selectOne(wrapper);

                if(bgNums.add(arr.getTe011()).add(arr.getUdf51()).add(arr.getUdf52()).add(arr.getUdf53()).compareTo(d420.getTE011()) > 0) {
                    throw new CustomException("500", "报工单, 合格数量:" + arr.getTe011() + ", + 工废数量:" + arr.getUdf51() + ", + 料废数量:" + arr.getUdf52() + " , + 不良数量:" + arr.getUdf53() + " , + 已报工数量:" + bgNums + " 大于 " +
                            "派工数量: " + d420.getTE011() + " !!");
                }

                sfcte.setTE011(arr.getTe011());
                sfcte.setUDF51(arr.getUdf51());
                sfcte.setUDF52(arr.getUdf52());
                sfcte.setUDF53(arr.getUdf53());
                sfcte.setTE023(nowTime.substring(0, 8));
                sfcte.setTE024(arr.getTd004());
                sfcte.setCREATE_DATE(nowTime);
                sfcte.setTE017(d420.getTE017());
                sfcte.setTE018(d420.getTE018());
                sfcte.setTE019(d420.getTE019());
                sfcte.setTE020(d420.getTE020());
                sfcte.setTE006(arr.getTe006());
                sfcte.setTE007(arr.getTe007());
                this.sfcteMapper.insert(sfcte);

                if (sfcta1!=null) {
                    if(com.example.untils.StringUtils.isEmpty(sfcta1.getTA030())) sfcta1.setTA030(nowTime.substring(0, 8));
                    sfcta1.setTA031(nowTime.substring(0, 8));
                    sfcta1.setTA011(sfcta1.getTA011() == null ? arr.getTe011() : sfcta1.getTA011().add(arr.getTe011()));
                    sfcta1.setUDF51(sfcta1.getUDF51() == null ? arr.getUdf51() : sfcta1.getUDF51().add(arr.getUdf51()));
                    sfcta1.setUDF52(sfcta1.getUDF52() == null ? arr.getUdf52() : sfcta1.getUDF52().add(arr.getUdf52()));
                    sfcta1.setUDF53(sfcta1.getUDF53() == null ? arr.getUdf53() : sfcta1.getUDF53().add(arr.getUdf53()));
                    sfctaMapper.update(sfcta1, wrapper);
                }
//                    } else {
//                        throw new YiFeiException(500, "此" + arr.getTe001() + "-" + arr.getTe002() + "派工单错误,无法报工!");
//                    }
            };
        }
        return Result.success("报工成功!");
    }

    @Override
    @Transactional
    public Result deleteSfcTdAndSfcTe(String single,String odd) {
        try{
            if (single.equals("D410")){
                deleSfctd(single, odd);
                return Result.success("此"+single+"-"+odd+"报工单已删除!");
            }else {
                BigDecimal te011 = this.sfcteMapper.getSfcTe(single,odd);
                if (Double.parseDouble(String.valueOf(te011))==0.0){
                    deleSfctd(single, odd);
                    return Result.success("此"+single+"-"+odd+"派工单已删除!");
                }else {
                    return Result.error("此"+single+"-"+odd+"派工单已存在报工单,无法删除!");
                }
            }
        }catch (Exception e){
            throw new YiFeiException(500,"删除发生异常"+e.getMessage());
        }
    }

    private void deleSfctd(String single, String odd) {
        int delete = this.sfctdMapper.deleteBySfcteListInteger(single,odd);
        if (delete>0){
            this.sfcteMapper.delete(new LambdaQueryWrapper<SFCTE>().eq(SFCTE::getTE001, single).eq(SFCTE::getTE002, odd));
        }
    }

    @Override
    public Result querySfcTdIPage(Integer current, Integer size,SelectDto selectDto) {
        try {
            Map<String,Object> map = new HashMap<>();
            PageHelper.startPage(current,size, "TE023 DESC");
            List<SfcTdVo> sfcTdVoList = this.sfctdMapper.querySfcTdIPage(selectDto);
            PageInfo<SfcTdVo> coptnPageInfo = new PageInfo<>(sfcTdVoList);
            map.put("pages", coptnPageInfo.getPages());
            map.put("total", coptnPageInfo.getTotal());
            map.put("list", coptnPageInfo.getList());
            return Result.success(map);
        }catch (Exception e){
            throw new YiFeiException(500, "派工单查询报错"+e.getMessage());
        }
    }

    @Override
    public Result<MocTaAndSfcTeVo> queryOneMocTa(String te001, String te002) {
        MocTaAndSfcTeVo mocTaAndSfcTeVo = this.sfcteMapper.queryMocTaAndSfcTe(te001, te002);
        if (mocTaAndSfcTeVo!=null){
            List<SfcTeListVo> sfcTeListVoList = this.sfcteMapper.querySfcTeListVo(mocTaAndSfcTeVo.getTe001(), mocTaAndSfcTeVo.getTe002());
            if (!sfcTeListVoList.isEmpty()){
                mocTaAndSfcTeVo.setSfcTeListVos(sfcTeListVoList);
                for(SfcTeListVo item : sfcTeListVoList) {
                    if(com.example.untils.StringUtils.isEmpty(item.getUdf07()) && com.example.untils.StringUtils.isNotEmpty(item.getTe004())) {
                        Cmsmv one = cmsmvMapper.selectOne(new LambdaQueryWrapper<Cmsmv>().eq(Cmsmv::getMv001, item.getTe004()));
                        if(one != null) item.setUdf07(one.getMv002());
                    }
                }
            }
        }
        return Result.success(mocTaAndSfcTeVo);
    }

    // 声明全局锁
    private final Lock lock = new ReentrantLock();

    @Override
    @Transactional
    public Result saveSfcTdAndSfcTe(List<SfctdDto> sfctdList) {
        lock.lock();
        try{
            String uuid = UUID.randomUUID().toString();
            // 派工信息返回值
//            List<Returnvalue> msgList = new ArrayList<>();
            StringBuffer stringBuffer = new StringBuffer();
            String nowTime = new SimpleDateFormat("yyyyMMddHHmmss").
                    format(new Date()).replaceAll("-", "").
                    replaceAll(":", "").replaceAll(" ", "");
            if (!sfctdList.isEmpty()) {
                for (SfctdDto sfctd : sfctdList) {
                    SFCTD sfctd1 = new SFCTD();
                    // 获取当前时间
                    LocalDateTime currentTime = LocalDateTime.now();

                    DateTimeFormatter yyyyMM = DateTimeFormatter.ofPattern("yyyyMMdd");
                    sfctd1.setTD001("D420");
                    Long dh = commonMapper.getDH2("SFCTD", "TD002", "TD001", "D420");
                    if (dh == null) {
                        dh = Long.parseLong(currentTime.format(yyyyMM)+"001");
                    } else {
                        dh++;
                    }
                    sfctd1.setTD002(""+dh);
                    sfctd1.setTD003(nowTime.substring(0,8));
                    sfctd1.setTD004(sfctd.getTD004());
                    sfctd1.setUDF01(uuid);
                    sfctd1.setUDF02(sfctd.getUDF02());
                    if(com.example.untils.StringUtils.isEmpty(sfctd.getUDF02())) {
                        throw new CustomException("500", "排产表MOCTY中的UUID不能为空!");
                    }
                    sfctd1.setCREATE_DATE(nowTime);
                    sfctd1.setCREATOR(SecurityUtils.getLoginUser().getUsername());
                    if (!sfctd.getSfcteList().isEmpty()) {
                        for (SfcteDto arr : sfctd.getSfcteList()) {
                            Long ta015 = this.sfcteMapper.querymocta(arr.getTE006(), arr.getTE007());
                            if (ta015!=null){
                                Integer integer = this.sfcteMapper.querySfCtePgNum(arr.getTE006(),arr.getTE007(), sfctd.getUDF02());
                                int num = Integer.parseInt(String.valueOf(ta015)) - integer;
                                if (num >= Integer.parseInt(String.valueOf(arr.getTE011())) && Integer.parseInt(String.valueOf(arr.getTE011())) > 0) {
                                    arr.setTE001(sfctd1.getTD001());
                                    arr.setTE002(sfctd1.getTD002());
                                    arr.setTE003(SerialNumberSfcte(sfctd1.getTD001(), sfctd1.getTD002()));
                                    arr.setUDF54(new BigDecimal(0));
                                    arr.setUDF55(new BigDecimal(0));
                                    arr.setUDF56(new BigDecimal(0));
                                    arr.setUDF57(new BigDecimal(ta015));
                                    //设置派工日期
                                    arr.setTE023(nowTime.substring(0, 8));
                                    arr.setTE024(sfctd.getTD004());
                                    arr.setTE030("1");
                                    arr.setCREATE_DATE(nowTime);
                                    sfctd1.setUDF51(arr.getTE011());

                                    Integer insert = this.sfcteMapper.saveSfcTeDto(arr);
//                                    Integer insert = 0;
//                                    if (insert > 0) {
//                                        Returnvalue returnvalue = new Returnvalue();
//                                        returnvalue.setCode(200);
////                                        returnvalue.setValue(uuid);
//                                        returnvalue.setValue(arr.getTE006() + "-" + arr.getTE007() + "派工成功");
//                                        msgList.add(returnvalue);
//                                    }
                                } else {
                                    throw new CustomException("500", arr.getTE006() + "-" + arr.getTE007() + "派工失败,此工单还可派工数量为:" + num + ",请重试!");
//                                    returnvalue.setValue(arr.getTE006()+"-"+arr.getTE007()+"-"+arr.getTE008()+"派工失败,此工序还可派工数量为:"+num+",请重试!");
                                }
                            }else {
                                throw new CustomException("500", arr.getTE006()+"-"+arr.getTE007()+"-"+"派工失败,此工单不存在");
                            }
                        }
                    }
                    this.sfctdMapper.save(sfctd1);
                    stringBuffer.append("派工单号: " + sfctd1.getTD001() + "-" + sfctd1.getTD002() + "\n");
                }
            }else {
                throw new YiFeiException(500,"派工失败,请输入正确的参数");
            }
            return Result.success(stringBuffer.toString());
        }finally {
            lock.unlock();  // 确保在完成后释放锁
        }
    }

    @Override
    public Result quxiao(String code) {
        this.sfcteMapper.updateYourEntityS(code);
        return Result.success();
    }

    @Override
    public Result queryById(Pojo pojo) {
        SFCTE sfcte = this.sfcteMapper.queryById(pojo);
        if (sfcte==null){
            return Result.success();
        }
        QueryWrapper<Qmsmg> qmsmgQueryWrapper = new QueryWrapper<>();
        qmsmgQueryWrapper.eq("MG002", pojo.getArticle().trim());// 品号
        qmsmgQueryWrapper.eq("MG020", pojo.getChecky().trim()); //检验项目
        qmsmgQueryWrapper.eq("MG008", pojo.getGy().trim()); // 区分工艺
        if (!StringUtils.isBlank(pojo.getRomm())){
            qmsmgQueryWrapper.eq("UDF06", pojo.getRomm()); // 场地
        }
        List<Qmsmg> qmsmgs = this.qmsmgMapper.selectList(qmsmgQueryWrapper);
        if (!qmsmgs.isEmpty()) {
            sfcte.setQmsmgList(qmsmgs);
        }
        MocVo mocVo = new MocVo();
        mocVo.setSingetsu(sfcte.getTE001());
        mocVo.setOdd(sfcte.getTE002());
        mocVo.setShijian(sfcte.getTE023());
        mocVo.setSbm(sfcte.getTE005());
        mocVo.setGx(sfcte.getTE008());
        mocVo.setPinhao(sfcte.getTE017());
        mocVo.setGy(sfcte.getTE009());
        mocVo.setGg(sfcte.getTE019());
        mocVo.setPm(sfcte.getTE018());
        mocVo.setJy(pojo.getChecky());
        mocVo.setZx(sfcte.getUDF10());
        mocVo.setScx(sfcte.getUDF09());
        mocVo.setQmsmgList(sfcte.getQmsmgList());
        mocVo.setStatus(sfcte.getStatus());
        return Result.success(mocVo);
    }

    @Override
    public Result test(String code) {
        this.sfcteMapper.updateYourEntity(code);
        return Result.success();
    }

    @Override
    public Result queryPageList(Pojo pojo) {
        try {
            PageHelper.startPage(pojo.getCurrent(),pojo.getSize());
            Map<String,Object> map = new HashMap<>();
            List<SFCTE> sfcteList = this.sfcteMapper.queryPageTest(pojo);
            PageInfo<SFCTE> pageInfo = new PageInfo<>(sfcteList);
            List<MocVo> mocVoList = pageInfo.getList().stream()
                    .map(arr -> {
                        MocVo mocVo = new MocVo();
                        mocVo.setSingetsu(arr.getTE001());
                        mocVo.setOdd(arr.getTE002());
                        mocVo.setShijian(arr.getTE023());
                        mocVo.setSbm("1");
                        mocVo.setGx(arr.getTE008());
                        mocVo.setPinhao(arr.getTE017());
                        mocVo.setGy(arr.getTE009());
                        mocVo.setGg(arr.getTE019());
                        mocVo.setPm(arr.getTE018());
                        mocVo.setJy(pojo.getChecky());
                        mocVo.setZx(arr.getUDF10());
                        mocVo.setStatus(arr.getStatus());
                        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");
                        String format = dateFormat.format(new Date());
                        mocVo.setTime(format);
                        mocVo.setScx(arr.getUDF09());
                        return mocVo;
                    })
                    .collect(Collectors.toList());
            map.put("total",pageInfo.getTotal());
            map.put("page",pageInfo.getPages());
            map.put("data",mocVoList);
            return Result.success(map);
        }catch (Exception e){
            return Result.error("品号分页查询发生异常错误"+e.getMessage());
        }
    }

    @Override
    public Result<SFCTE> detailPB(String TE001, String TE002) {
        try {
            SFCTE sfcte = this.sfcteMapper.selectOne(new QueryWrapper<SFCTE>().eq("TE001", TE001).eq("TE002", TE002));
            return Result.success(sfcte);
        }catch (Exception e){
            throw new YiFeiException(500,"详情查询发生异常"+e.getMessage());
        }
    }

    //    @Override
    public Result deleteDp(String TE001, String TE002) {
        try{
            SFCTE sfcte = this.sfcteMapper.selectOne(new QueryWrapper<SFCTE>().eq("TE001", TE001).eq("TE002", TE002));
            if (sfcte!=null){
                List<SFCTE> sfcteList = this.sfcteMapper.querySfCte(sfcte.getTE006(), sfcte.getTE007(), sfcte.getTE008());
                if (!sfcteList.isEmpty()){
                    int delete = this.sfcteMapper.delete(new QueryWrapper<SFCTE>().eq("TE001", TE001).eq("TE002", TE002));
                    if (delete>0){
                        return Result.success(TE001+"-"+TE002+"派工单已删除!");
                    }
                }
                return Result.error("此"+TE001+"-"+TE002+"派工单已存在报工单,无法删除!");
            }
            return Result.error("此"+TE001+"-"+TE002+"派工单不存在,请重试!");
        }catch (Exception e){
            throw new YiFeiException(500,"报工单删除发生异常"+e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result deleteDb(String TE001, String TE002) {

            if (TE001.equals("D410")){
                SFCTE sfcte = this.sfcteMapper.selectOne(new QueryWrapper<SFCTE>().eq("TE001", TE001).eq("TE002", TE002));
                if (sfcte==null){
                    return Result.error("此"+TE001+"-"+TE002+"报工单不存在,无法删除!");
                }
                int delete = this.sfcteMapper.delete(new QueryWrapper<SFCTE>().eq("TE001", TE001).eq("TE002", TE002));
                if (delete>0){
                    Integer deletesfctd = this.sfcteMapper.deletesfctd(TE001, TE002);
                    if (deletesfctd>0){
                        SFCTE pg = this.sfcteMapper.getByTE001WithTE002WithTE003(sfcte.getUDF09(), sfcte.getUDF10(), sfcte.getUDF11());
                        BigDecimal te011bg = this.sfcteMapper.getTE011WithTE001WithTE006WithTE007WithTE008(pg.getTE001(), pg.getTE002(), pg.getTE003());
                        if (Double.parseDouble(String.valueOf(pg.getTE011()))>Double.parseDouble(String.valueOf(te011bg))){
                            this.sfcteMapper.updateBg(sfcte.getTE001()+"-"+sfcte.getTE002()+"-"+sfcte.getTE003(),"N");
                        }
                        return Result.success(TE001+"-"+TE002+"报工单已删除!");
                    }else {
                        return Result.success(TE001+"-"+TE002+"报工单删除失败!");
                    }
                }
                return Result.error(TE001+"-"+TE002+"报工单删除失败!");
            } else {
                SFCTE sfcte = this.sfcteMapper.selectOne(new QueryWrapper<SFCTE>().eq("TE001", TE001).eq("TE002", TE002));
                if (sfcte==null){
                    return Result.error("此"+TE001+"-"+TE002+"派工单不存在,无法删除!");
                }
                BigDecimal te011 = this.sfcteMapper.getTE011WithTE001WithTE006WithTE007WithTE008(sfcte.getTE001(), sfcte.getTE002(), sfcte.getTE003());
                if (Double.parseDouble(String.valueOf(te011))==0.0){
                    int delete = this.sfcteMapper.delete(new QueryWrapper<SFCTE>().eq("TE001", TE001).eq("TE002", TE002));
                    if (delete>0){
                        return Result.success(TE001+"-"+TE002+"派工单已删除!");
                    }
                }
                return Result.error("此"+TE001+"-"+TE002+"派工单已存在报工单,无法删除!");
            }

    }

    @Override
    public Result queryRejects(SelectDto selectDto) {
        Map<String,Object> map =new HashMap<>();
        IPage<SFCTE> iPage = new Page<>(selectDto.getCurrent(),selectDto.getSize());

        QueryWrapper<SFCTE> sfcteQueryWrapper = new QueryWrapper<>();
        sfcteQueryWrapper.eq("TE001","D410");
        sfcteQueryWrapper.ne("UDF51",0);

        // 通过工单号进行查询
        if (!StringUtils.isBlank(selectDto.getNumber())){
            sfcteQueryWrapper.like("TE006 + '-' + TE007",selectDto.getNumber());
        }
        // 通过工艺行查询
        if (!StringUtils.isBlank(selectDto.getCraft())){
            sfcteQueryWrapper.like("TE009",selectDto.getCraft());
        }
        // 通过工作中心进行查询
        if (!StringUtils.isBlank(selectDto.getWorkCenter())){
            sfcteQueryWrapper.like("UDF10",selectDto.getWorkCenter());
        }
        // 通过订单号进行查询
        if (!StringUtils.isBlank(selectDto.getOrderNumber())){
            sfcteQueryWrapper.like("UDF04",selectDto.getOrderNumber());
        }
        // 通过品号查询
        if (!StringUtils.isBlank(selectDto.getItemNo())){
            sfcteQueryWrapper.like("TE017",selectDto.getItemNo());
        }
        // 通过员工姓名查询
        if (!StringUtils.isBlank(selectDto.getName())){
            sfcteQueryWrapper.like("UDF07",selectDto.getName());
        }
        // 通过时间区域查询
        if (!StringUtils.isBlank(selectDto.getStartTime())&&!StringUtils.isBlank(selectDto.getEndTime())){
            sfcteQueryWrapper.between("TE023",selectDto.getStartTime(),selectDto.getEndTime());
        }


        // 通过时间排序
        sfcteQueryWrapper.orderByDesc("TE023");
        IPage<SFCTE> sfcteiPage = this.sfcteMapper.selectPage(iPage, sfcteQueryWrapper);

        map.put("page",sfcteiPage.getPages());
        map.put("data",sfcteiPage.getRecords());
        map.put("total",sfcteiPage.getTotal());

        return Result.success(map);
    }

    @Override
    public Result querySfCtaIPag(PojoDto pojoDto) {
        try{
            PageHelper.startPage(pojoDto.getCurrent(),pojoDto.getSize());
            List<SfctaMoctaVo> sfctaMoctaVos = this.sfcteMapper.querySfCtaIPag(pojoDto);
            sfctaMoctaVos.stream().forEach(arr-> {
                        Cmsme cmsme = cmsmeMapper.getByME001(arr.getTa064());
                        if (cmsme != null) {
                            arr.setDname(cmsme.getMe002());
                        }
                    }
            );
            PageInfo<SfctaMoctaVo> pageInfo = new PageInfo<>(sfctaMoctaVos);
            Map<String,Object> map = new HashMap<>();
            map.put("page",pageInfo.getPages());
            map.put("data",pageInfo.getList());
            map.put("total",pageInfo.getTotal());
            return Result.success(map);
        }catch (Exception e){
            throw new YiFeiException(500,"错误"+e.getMessage());
        }
    }

    @Override
    public List<SFCTA> querySfCta(String TA001, String TA002) {
        QueryWrapper<SFCTA> sfctaQueryWrapper = new QueryWrapper<>();
        sfctaQueryWrapper.eq("TA001",TA001);
        sfctaQueryWrapper.eq("TA002",TA002);
        List<SFCTA> sfctas = this.sfctaMapper.selectList(sfctaQueryWrapper);
        if (sfctas.isEmpty()){
            throw new YiFeiException(500,"此单别单号暂无工单工艺信息!");
        }
        return sfctas;
    }

    @Override
    @Transactional
    public Result insertSfcte(List<SFCTE> sfcte) {
        try{
            // 派工信息返回值
            List<String> msgList = new ArrayList<>();
            String nowTime = new SimpleDateFormat("yyyyMMddHHmmss").
                    format(new Date()).replaceAll("-", "").
                    replaceAll(":", "").replaceAll(" ", "");
            if (!sfcte.isEmpty()){
                sfcte.stream().forEach(arr -> {
                    Long ta015 = this.sfcteMapper.querymocta(arr.getTE006(), arr.getTE007());
                    if (ta015!=null){
                        Integer integer = this.sfcteMapper.querySfCtePgNum(arr.getTE006(),arr.getTE007(),arr.getTE008());
                        int num = Integer.parseInt(String.valueOf(ta015)) - integer;
                        if (num>=Integer.parseInt(String.valueOf(arr.getTE011()))&&Integer.parseInt(String.valueOf(arr.getTE011()))>0){
                            arr.setTE001("D420");
                            arr.setTE002(sfcteMapper.getNewTE002Year4("D420"));
                            arr.setTE003(SerialNumber(arr.getTE006(),arr.getTE007(),arr.getTE008()));
                            arr.setUDF54(new BigDecimal(0));
                            arr.setUDF55(new BigDecimal(0));
                            arr.setUDF56(new BigDecimal(0));
                            arr.setUDF57(new BigDecimal(ta015));
                            //设置派工日期
                            arr.setTE023(nowTime.substring(0,8));
                            arr.setCREATE_DATE(nowTime);
                            int insert = this.sfcteMapper.insert(arr);
                            if (insert>0){
                                msgList.add(arr.getTE006()+"-"+arr.getTE007()+"-"+arr.getTE008()+"派工成功");
                            }
                        }else{
                            msgList.add(arr.getTE006()+"-"+arr.getTE007()+"-"+arr.getTE008()+"派工失败,此工序还可派工数量为:"+num+",请重试!");
                        }
                    }else {
                        msgList.add(arr.getTE006()+"-"+arr.getTE007()+"-"+arr.getTE008()+"派工失败,此工序不存在");
                    }
                });
            }else {
                throw new YiFeiException(500,"派工失败,请输入正确的参数");
            }
            return Result.success(msgList);
        }catch (Exception e){
            throw new YiFeiException(500,"派工单新增发生异常,请联系管理员"+e);
        }
    }

    public Result querySfCtAMoCtaList(Integer pageNum, Integer pageSize,String TA001,String TA002,String TA006,String TA003) {
        PageHelper.startPage(pageNum,pageSize);
        List<SfctaMoctaVo> sfctaMoctaVos = this.sfcteMapper.querySfCtAMoCtaList(TA001,TA002,TA006,TA003);
        sfctaMoctaVos.stream().forEach(arr-> {
                    // 此工单工艺的报工数量
                    Integer integer = this.sfcteMapper.querySfCteNum(arr.getTa001(), arr.getTa002(), arr.getTa003());
                    arr.setNum(BigDecimal.valueOf(integer));
                    double v = Double.parseDouble(String.valueOf(integer)) / Double.parseDouble(String.valueOf(arr.getTa015()));
                    DecimalFormat df = new DecimalFormat("#.0");
                    String formattedValue = df.format(v*100.00);
                    arr.setPercent(formattedValue);
                    String pdf = invmbMapper.getMB029(arr.getTa006());
                    arr.setPdf(url + StringUtils.toStringTrim(pdf)+".pdf");
                    Cmsme cmsme = cmsmeMapper.getByME001(arr.getTa064());
                    String UDF03 = "" ;
                    if (cmsme != null) {
                        UDF03 = cmsme.getMe002();
                    }
                    arr.setDname(UDF03);
                }
        );
        PageInfo<SfctaMoctaVo> pageInfo = new PageInfo<>(sfctaMoctaVos);
        Map<String,Object> map = new HashMap<>();
        map.put("page",pageInfo.getPages());
        map.put("data",pageInfo.getList());
        map.put("total",pageInfo.getTotal());
        return Result.success(map);
    }

    @Override
    public Result queryMoCtaSfCtAListAll(Integer pageNum, Integer pageSize,String TA001,String TA002,String TA006,String TA011) {
        PageHelper.startPage(pageNum,pageSize);
        List<MoctastaVo> moctastaVos = this.sfcteMapper.queryMoCtaSfCtAListAll(TA001, TA002, TA006,TA011);
        if (!moctastaVos.isEmpty()){
            moctastaVos.stream().forEach(arr-> {
                        List<SFCTAVo> sfctaVos = this.sfcteMapper.querySfctaVo(arr.getTa001(), arr.getTa002());
                        if (!sfctaVos.isEmpty()){
                            sfctaVos.forEach(arrs -> {
                                // 此工单工艺的报工数量
                                SfcteVo sfcteVo = this.sfcteMapper.querySfCteNums(arrs.getTa001(), arrs.getTa002(), arrs.getTa003());
                                arrs.setNum(BigDecimal.valueOf(sfcteVo.getNum()));
                                double v = Double.parseDouble(String.valueOf(sfcteVo.getNum())) / Double.parseDouble(String.valueOf(arr.getTa015()));
                                DecimalFormat df = new DecimalFormat("#.0");
                                String formattedValue = df.format(v*100.00);
                                arrs.setPercent(formattedValue);
                                arrs.setBlmun(sfcteVo.getBlnum());
                            });
                        }
                        arr.setSfctaVos(sfctaVos);
                    }
            );
        }
        PageInfo<MoctastaVo> pageInfo = new PageInfo<>(moctastaVos);
        Map<String,Object> map = new HashMap<>();
        map.put("page",pageInfo.getPages());
        map.put("data",pageInfo.getList());
        map.put("total",pageInfo.getTotal());
        return Result.success(map);
    }

    @Override
    public List<SFCTE> querySfCte(String odd,String Single,String Gx) {
        List<SFCTE> sfcteList = this.sfcteMapper.querySfCte(odd, Single, Gx);
        return sfcteList;
    }

    public List<SFCTE> querySfCteS(String odd,String Single,String Gx) {
        List<SFCTE> sfcteList = this.sfcteMapper.querySfCte(odd, Single, Gx);
        return sfcteList;
    }

    @Override
    public Result queryIPage(SelectDto selectDto) {
        Map<String,Object> map =new HashMap<>();
        IPage<SFCTE> iPage = new Page<>(selectDto.getCurrent(),selectDto.getSize());

        QueryWrapper<SFCTE> sfcteQueryWrapper = new QueryWrapper<>();
        sfcteQueryWrapper.eq("TE001","D410");

        // 通过工单号进行查询
        if (!StringUtils.isBlank(selectDto.getNumber())){
            sfcteQueryWrapper.like("TE006 + '-' + TE007",selectDto.getNumber());
        }
        // 通过工艺行查询
        if (!StringUtils.isBlank(selectDto.getCraft())){
            sfcteQueryWrapper.like("TE009",selectDto.getCraft());
        }
        // 通过工作中心进行查询
        if (!StringUtils.isBlank(selectDto.getWorkCenter())){
            sfcteQueryWrapper.like("TE024",selectDto.getWorkCenter());
        }
        // 通过订单号进行查询
        if (!StringUtils.isBlank(selectDto.getOrderNumber())){
            sfcteQueryWrapper.like("UDF04",selectDto.getOrderNumber());
        }
        // 通过品号查询
        if (!StringUtils.isBlank(selectDto.getItemNo())){
            sfcteQueryWrapper.like("TE017",selectDto.getItemNo());
        }
        // 通过员工姓名查询
        if (!StringUtils.isBlank(selectDto.getName())){
            sfcteQueryWrapper.like("UDF07",selectDto.getName());
        }
        // 通过时间区域查询
        if (!StringUtils.isBlank(selectDto.getStartTime())&&!StringUtils.isBlank(selectDto.getEndTime())){
            sfcteQueryWrapper.between("TE023",selectDto.getStartTime(),selectDto.getEndTime());
        }

        // 通过时间排序
        sfcteQueryWrapper.orderByDesc("TE023");
        IPage<SFCTE> sfcteiPage = this.sfcteMapper.selectPage(iPage, sfcteQueryWrapper);

        if(!sfcteiPage.getRecords().isEmpty()){
            sfcteiPage.getRecords().forEach(arr -> {
                Cmsmd byMD001 = this.cmsmdMapper.getByMD001(arr.getTE024());
                if (byMD001!=null){
                    arr.setMD002(byMD001.getMd002());
                }
            });
        }

        map.put("page",sfcteiPage.getPages());
        map.put("data",sfcteiPage.getRecords());
        map.put("total",sfcteiPage.getTotal());

        return Result.success(map);
    }

    @Override
    public Result queryIPageS(SelectDto selectDto) {
        Map<String,Object> map =new HashMap<>();
        IPage<SFCTE> iPage = new Page<>(selectDto.getCurrent(),selectDto.getSize());

        QueryWrapper<SFCTE> sfcteQueryWrapper = new QueryWrapper<>();
        sfcteQueryWrapper.eq("TE001","D420");

        // 通过工单号进行查询
        if (!StringUtils.isBlank(selectDto.getNumber())){
            sfcteQueryWrapper.like("TE006 + '-' + TE007",selectDto.getNumber());
        }
        // 通过工艺行查询
        if (!StringUtils.isBlank(selectDto.getCraft())){
            sfcteQueryWrapper.like("TE009",selectDto.getCraft());
        }
        // 通过工作中心进行查询
        if (!StringUtils.isBlank(selectDto.getWorkCenter())){
            sfcteQueryWrapper.like("UDF10",selectDto.getWorkCenter());
        }
        // 通过订单号进行查询
        if (!StringUtils.isBlank(selectDto.getOrderNumber())){
            sfcteQueryWrapper.like("UDF04",selectDto.getOrderNumber());
        }
        // 通过品号查询
        if (!StringUtils.isBlank(selectDto.getItemNo())){
            sfcteQueryWrapper.like("TE017",selectDto.getItemNo());
        }
        // 通过员工姓名查询
        if (!StringUtils.isBlank(selectDto.getName())){
            sfcteQueryWrapper.like("UDF07",selectDto.getName());
        }
        // 通过时间区域查询
        if (!StringUtils.isBlank(selectDto.getStartTime())&&!StringUtils.isBlank(selectDto.getEndTime())){
            sfcteQueryWrapper.between("TE023",selectDto.getStartTime(),selectDto.getEndTime());
        }

        // 通过时间排序
        sfcteQueryWrapper.orderByDesc("TE023");
        IPage<SFCTE> sfcteiPage = this.sfcteMapper.selectPage(iPage, sfcteQueryWrapper);

        map.put("page",sfcteiPage.getPages());
        map.put("data",sfcteiPage.getRecords());
        map.put("total",sfcteiPage.getTotal());

        return Result.success(map);
    }

    @Override
    public List<SFCTE> selectListByDbDh(String single, String odd) {
        List<SFCTE> sfcteList = sfcteMapper.getListByTE001WithTE002(single,odd);
        for (SFCTE sfcte : sfcteList) {
            // 查询已报工数量
            BigDecimal TE011 = sfcteMapper.getTE011WithTE001WithTE006WithTE007WithTE008("D420",sfcte.getTE002(),sfcte.getTE003());
            // 设置工单数量 select TA015 from where TA001 = '' and TA002 = ''
            MOCTA mocta = moctaMapper.getByTA001WithTA002(sfcte.getTE006(), sfcte.getTE007());
            sfcte.setUDF58(mocta.getTA015());
            sfcte.setUDF59(TE011);
            sfcte.setUDF57(sfcte.getTE011());
            double v = Double.parseDouble(String.valueOf(TE011)) / Double.parseDouble(String.valueOf(sfcte.getTE011()));
            DecimalFormat df = new DecimalFormat("#.0");
            String formattedValue = df.format(v*100.00);
            sfcte.setPercent(formattedValue);

            // 根据工单单笔单号加工序号查询对应的工单工艺详情
            SFCTA sfcta = sfctaMapper.getByTA001WithTA002WithTA003(sfcte.getTE006(), sfcte.getTE007(), sfcte.getTE008());
            if (sfcta!=null){
                //TODO 客户TA019有区别，后续可能还需要切换并且修改实体类
                sfcte.setUDF12(sfcta.getTA019());
                if (StringUtils.isBlank(sfcte.getUDF12())){
                    String pdf = invmbMapper.getMB029(sfcte.getTE017());
                    sfcte.setUDF04(url + StringUtils.toStringTrim(pdf)+".pdf");
                }else {
                    String pdf = invmbMapper.getMB029(sfcte.getUDF12());
                    sfcte.setUDF04(url + StringUtils.toStringTrim(pdf)+".pdf");
                }
                //根据sfcta中的工作中心找到对应的部门编号
                Cmsmd cmsmd = cmsmeMapper.getByMD001(sfcta.getTA006());
                // 根据工作中心的部门找到对应的部门编号 和 部门名称
                // UDF02我们设置部门编号
                sfcte.setUDF02(cmsmd.getMd015());
                Cmsme cmsme = cmsmeMapper.getByME001(cmsmd.getMd015());
                String UDF03 = "" ;
                if (cmsme != null) {
                    UDF03 = cmsme.getMe002();
                }
                // UDF03我们设置为部门名称
                sfcte.setUDF03(UDF03);
//            sfcte.setUDF06(sfcte.getTE007());
                System.out.println(UDF03);
            }
        }
        return sfcteList;
    }

    @Override
    public List<SFCTE> selectListStaff(String code) {
        Cmsmv cmsmv = this.cmsmvMapper.selectOne(new QueryWrapper<Cmsmv>().eq("MV079",code));
        List<SFCTE> sfcteList = sfcteMapper.selectListStaff(cmsmv.getMv001());
        for (SFCTE sfcte : sfcteList) {
            // 查询已报工数量
            BigDecimal TE011 = sfcteMapper.getTE011WithTE001WithTE006WithTE007WithTE008("D420",sfcte.getTE002(),sfcte.getTE003());
            // 设置工单数量 select TA015 from where TA001 = '' and TA002 = ''
            MOCTA mocta = moctaMapper.getByTA001WithTA002(sfcte.getTE006(), sfcte.getTE007());
            if (mocta!=null){
                sfcte.setUDF58(mocta.getTA015());
            }
            sfcte.setUDF59(TE011);
            sfcte.setUDF57(sfcte.getTE011());
            double v = Double.parseDouble(String.valueOf(TE011)) / Double.parseDouble(String.valueOf(sfcte.getTE011()));
            DecimalFormat df = new DecimalFormat("#.0");
            String formattedValue = df.format(v*100.00);
//            System.out.println("值2"+v);
//            System.out.println("值："+formattedValue);
            sfcte.setPercent(formattedValue);

            // 根据工单单笔单号加工序号查询对应的工单工艺详情
            SFCTA sfcta = sfctaMapper.getByTA001WithTA002WithTA003(sfcte.getTE006(), sfcte.getTE007(), sfcte.getTE008());
            if (sfcta!=null){
                //TODO 客户TA019有区别，后续可能还需要切换并且修改实体类
                sfcte.setUDF12(sfcta.getTA019());
                if (StringUtils.isBlank(sfcte.getUDF12())){
                    String pdf = invmbMapper.getMB029(sfcte.getTE017());
                    sfcte.setUDF04(url + StringUtils.toStringTrim(pdf)+".pdf");
                }else {
                    String pdf = invmbMapper.getMB029(sfcte.getUDF12());
                    sfcte.setUDF04(url + StringUtils.toStringTrim(pdf)+".pdf");
                }
                //根据sfcta中的工作中心找到对应的部门编号
                Cmsmd cmsmd = cmsmeMapper.getByMD001(sfcta.getTA006());
                // 根据工作中心的部门找到对应的部门编号 和 部门名称
                // UDF02我们设置部门编号
                sfcte.setUDF02(cmsmd.getMd015());
                Cmsme cmsme = cmsmeMapper.getByME001(cmsmd.getMd015());
                String UDF03 = "" ;
                if (cmsme != null) {
                    UDF03 = cmsme.getMe002();
                }
                // UDF03我们设置为部门名称
                sfcte.setUDF03(UDF03);
//            sfcte.setUDF06(sfcte.getTE007());
                System.out.println(UDF03);
            }
        }

        return sfcteList;
    }

    @Override
    public Result add(SFCTE sfcte) {
        try {
//            System.out.println("报工"+sfcte);
            log.info(sfcte.toString());
            SFCTE findSFcte = sfcteMapper.getByTE001WithTE002WithTE003(sfcte.getTE001(),sfcte.getTE002(),sfcte.getTE003());
            log.info(findSFcte.toString());
            if (findSFcte==null){
                return Result.error("派工单号不存在");
            }
            if(findSFcte.getUDF08()!=null){
                if (findSFcte.getUDF08().equals("Y")){
                    return Result.error("派工单报工结束,无需要重复报工");
                }
            }
            List<SFCTE> sfcteList = this.sfcteMapper.gette001(findSFcte.getTE006(), findSFcte.getTE007(), findSFcte.getTE008());
            if (!sfcteList.isEmpty()){
                List<IHead> iHeads = this.iHeadMapper.queryTa001IHeadList(sfcteList.get(0).getTE001(), sfcteList.get(0).getTE002());
                if (!iHeads.isEmpty()){
                    if (iHeads.get(0).getResult().equals("N")){
                        return Result.error(iHeads.get(0).getTa001()+"-"+iHeads.get(0).getTa002()+"检验未合格,请勿报工!");
                    }
                }
            }
            SFCTE saveSFCTE =  new SFCTE();
            SFCTD saveSFCTD =  new SFCTD();
            String nowTime = new SimpleDateFormat("yyyyMMddHHmmss").
                    format(new Date()).replaceAll("-", "").
                    replaceAll(":", "").replaceAll(" ", "");
            //设置当前创建时间
            saveSFCTE.setCREATE_DATE(nowTime);

            String nowTimeNew = new SimpleDateFormat("yyyyMMddHHmmss").
                    format(new Date());
            saveSFCTD.setCREATE_DATE(nowTimeNew);

            saveSFCTE.setCREATOR(sfcte.getCREATOR());
            saveSFCTD.setCREATOR(sfcte.getCREATOR());
            // 设置报工单单别
            saveSFCTE.setTE001("D410");
            saveSFCTD.setTD001("D410");
            // 生成报工单单号
            saveSFCTE.setTE002(sfcteMapper.getNewTE002Year4("D410"));
            saveSFCTD.setTD002(sfcteMapper.getNewTE002Year4("D410"));

            String localDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            saveSFCTD.setTD003(localDate);
            saveSFCTD.setTD005("Y");
            saveSFCTD.setTD004(" ");
            saveSFCTD.setUDF01("白班");
            saveSFCTD.setTD008(localDate);
            sfctdMapper.save(saveSFCTD);
            // 设置序号
            saveSFCTE.setTE003(sfcte.getTE003());
            // 设置报工人员姓名
            saveSFCTE.setTE004(sfcte.getTE004());
            // 设置工单单别

            saveSFCTE.setTE006(findSFcte.getTE006());
            //设置工单单号
            saveSFCTE.setTE007(findSFcte.getTE007());
            // 设置工序
            saveSFCTE.setTE008(findSFcte.getTE008());
            // 设置工艺
            saveSFCTE.setTE009(findSFcte.getTE009());
            // 设置类型
            saveSFCTE.setTE010(findSFcte.getTE010());

            saveSFCTE.setTE011(sfcte.getTE011());
            //设置审核默认审核
            saveSFCTE.setTE014("Y");

            //设置备注
            saveSFCTE.setTE015(sfcte.getTE015());

            //设置   包装数量
            saveSFCTE.setTE016(findSFcte.getTE016());

            //设置产品品号
            saveSFCTE.setTE017(findSFcte.getTE017());

            //设置产品品名
            saveSFCTE.setTE018(findSFcte.getTE018());

            //设置产品规格
            saveSFCTE.setTE019(findSFcte.getTE019());

            //设置单位
            saveSFCTE.setTE020(findSFcte.getTE020());

            //设置包装单位
            saveSFCTE.setTE021(findSFcte.getTE021());

            //设置报工日期
            saveSFCTE.setTE023(nowTime.substring(0,8));

            //设置 预留字段
            saveSFCTE.setTE024(sfcte.getTE024());

            //设置 预留字段
            saveSFCTE.setTE025(sfcte.getTE025());

            //设置 预留字段
            saveSFCTE.setTE026(sfcte.getTE026());

            //设置 预留字段
            saveSFCTE.setTE027(sfcte.getTE027());

            //设置 计价单价
            saveSFCTE.setTE028(findSFcte.getTE028());

            //设置 工时工资率
            saveSFCTE.setTE029(findSFcte.getTE029());



            //设置 计件类型
            saveSFCTE.setTE030(findSFcte.getTE030());

            //设置j金额
            saveSFCTE.setTE031(sfcte.getTE031());

            //设置项目编号
            saveSFCTE.setTE032(findSFcte.getTE032());

            //设置工艺名称
            saveSFCTE.setUDF01(findSFcte.getUDF01());

            //设置UDF02
            saveSFCTE.setUDF02(sfcte.getUDF02());

            //设置UDF03
            saveSFCTE.setUDF03(sfcte.getUDF03());

            //设置UDF04
            saveSFCTE.setUDF04("");

            //设置UDF05
            saveSFCTE.setUDF05("");

            //设置工艺名称
            saveSFCTE.setUDF06(findSFcte.getUDF06());

            //设置工艺名称
            saveSFCTE.setUDF07(findSFcte.getUDF07());

            //设置工艺名称
            saveSFCTE.setUDF08(findSFcte.getUDF08());

            //设置工艺名称
            saveSFCTE.setUDF09(findSFcte.getTE001());

            //设置工艺名称
            saveSFCTE.setUDF10(findSFcte.getTE002());

            //设置工艺名称
            saveSFCTE.setUDF11(findSFcte.getTE003());

            //设置工艺名称
            saveSFCTE.setUDF12(sfcte.getUDF12());

            //设置工艺名称
            saveSFCTE.setUDF51(sfcte.getUDF51());

            //设置料废数量
            saveSFCTE.setUDF52(sfcte.getUDF52());

            //设置不良数量
            saveSFCTE.setUDF53(sfcte.getUDF53());

            //设置UDF54
            saveSFCTE.setUDF54(sfcte.getUDF53());

            //设置UDF55
            saveSFCTE.setUDF55(sfcte.getUDF53());

            //设置UDF56
            saveSFCTE.setUDF56(sfcte.getUDF53());

            //设置UDF57
            saveSFCTE.setUDF57(sfcte.getUDF57());

            //设置UDF58
            saveSFCTE.setUDF58(sfcte.getUDF58());

            //设置UDF59
            saveSFCTE.setUDF59(sfcte.getUDF59());

            //设置UDF60
            saveSFCTE.setUDF60(sfcte.getUDF60());

            //设置UDF61
            saveSFCTE.setUDF61(sfcte.getUDF61());

            //设置UDF62
            saveSFCTE.setUDF62(sfcte.getUDF62());

            //设置UDF05
            saveSFCTE.setUDF05(sfcte.getUDF05());

            saveSFCTE.setStatus("待检验");

            // 添加报工单
            sfcteMapper.save(saveSFCTE);


            BigDecimal te011bg = this.sfcteMapper.getTE011WithTE001WithTE006WithTE007WithTE008(sfcte.getTE001(), sfcte.getTE002(), sfcte.getTE003());
            if (Double.parseDouble(String.valueOf(te011bg))>=Double.parseDouble(String.valueOf(findSFcte.getTE011()))){
                this.sfcteMapper.updateBg(sfcte.getTE001()+"-"+sfcte.getTE002()+"-"+sfcte.getTE003(),"Y");
            }

            return Result.success("报工成功");
        }catch (Exception e){
            throw new YiFeiException(500,"报工错误发生异常:"+e.getMessage());
        }
    }


    public String SerialNumber(String te006,String te007,String te008) {
        QueryWrapper<SFCTE> dispatchListQueryWrapper = new QueryWrapper<>();
        dispatchListQueryWrapper.orderByDesc("TE003");
        dispatchListQueryWrapper.eq("TE006",te006);
        dispatchListQueryWrapper.eq("TE007",te007);
        dispatchListQueryWrapper.eq("TE008",te008);
        //查询最新的流水号
        List<SFCTE> sCells = sfcteMapper.selectList(dispatchListQueryWrapper);
        //用于保存获取最新的流水号
        String temp="";
        //用于拼接需要的流水号
        String serialNumber="";
        //保存最新的流水号
        if(!sCells.isEmpty()){
            temp=sCells.get(0).getTE003();
        }
        //判断数据库是否有数据
        if (!StringUtils.isBlank(temp)){
            Integer integer=Integer.valueOf(temp.trim())+1;
            if (integer>10){
                serialNumber="00"+String.valueOf(integer);
            }else {
                serialNumber="000"+String.valueOf(integer);
            }
        }else{
            serialNumber="0001";
        }
        return serialNumber;
    }

    public String SerialNumberSfcte(String te001,String te002) {
        QueryWrapper<SFCTE> dispatchListQueryWrapper = new QueryWrapper<>();
        dispatchListQueryWrapper.orderByDesc("TE003");
        dispatchListQueryWrapper.eq("TE001",te001);
        dispatchListQueryWrapper.eq("TE002",te002);
        //查询最新的流水号
        List<SFCTE> sCells = sfcteMapper.selectList(dispatchListQueryWrapper);
        //用于保存获取最新的流水号
        String temp="";
        //用于拼接需要的流水号
        String serialNumber="";
        //保存最新的流水号
        if(!sCells.isEmpty()){
            temp=sCells.get(0).getTE003();
        }
        //判断数据库是否有数据
        if (!StringUtils.isBlank(temp)){
            Integer integer=Integer.valueOf(temp.trim())+1;
            if (integer>10){
                serialNumber="00"+String.valueOf(integer);
            }else {
                serialNumber="000"+String.valueOf(integer);
            }
        }else{
            serialNumber="0001";
        }
        return serialNumber;
    }

    @Override
    public List<SFCTE> qualityFrom(String page,String pageSize, String udf06, String start_time,String end_time) {
        return sfcteMapper.qualityFrom(page,pageSize,udf06,start_time,end_time);
    }


    @Override
    public Result<List<GroupVo>> queryMocta() {
        List<SfcteAllVo> list = sfcteMapper.getUdf01();
        List<GroupVo>  groupVos = new ArrayList<>();

        for (SfcteAllVo sfcteAllVo : list) {
            GroupVo groupVo = new GroupVo();
            String udf01 = sfcteAllVo.getUdf01();
            List<SfcTeListVo> list1 = sfcteMapper.getlist(udf01);
            if (list1 == null || list1.isEmpty()) continue;
            groupVo.setSfcteAllVo(sfcteAllVo);
            groupVo.setSfcTeListVos(list1);
            groupVos.add(groupVo);
        }
        return Result.ok(groupVos);
    }

    @Override
    public List<SfcTeListVo> pgByUuid(String db,String dh) {
        List<SfcTeListVo> list = sfcteMapper.getSfcte(db, dh);
        for (SfcTeListVo sfcTeListVo : list) {
            SFCTA lastDishNum = sfctaMapper.getLastDishNum(sfcTeListVo.getTe006(), sfcTeListVo.getTe007(), sfcTeListVo.getTe008());
            if (lastDishNum == null){
                sfcTeListVo.setSGxYbNum(sfcTeListVo.getTe011().doubleValue());
            }else {
                sfcTeListVo.setSGxYbNum(lastDishNum.getTA011().doubleValue()+lastDishNum.getUDF51().doubleValue()+lastDishNum.getUDF52().doubleValue()+lastDishNum.getUDF53().doubleValue());
            }
        }
        return list;
    }

    @DSTransactional
    @Override
    public Result saveSfCTDandSFCTEprocess(List<SaveSfCTDandSFCTEprocessDto> sfctdList) {

        for(SaveSfCTDandSFCTEprocessDto item : sfctdList) {



        }

        return Result.ok();
    }

    @DSTransactional
    @Override
    public Result saveBGmocty(SaveBGmoctyDto dto) {
        String nowTime = TimeUtils.getNowTime();
        if(com.example.untils.StringUtils.isEmpty(dto.getTe006())) {
            throw new CustomException("500", "工单单别不能为空!");
        }
        if(com.example.untils.StringUtils.isEmpty(dto.getTe007())) {
            throw new CustomException("500", "工单单号不能为空!");
        }
        if(com.example.untils.StringUtils.isEmpty(dto.getTe008())) {
            throw new CustomException("500", "工单工序不能为空!");
        }
        if(com.example.untils.StringUtils.isEmpty(dto.getTe005())) {
            throw new CustomException("500", "机器编号不能为空!");
        }
        if(com.example.untils.StringUtils.isEmpty(dto.getTe024())) {
            throw new CustomException("500", "工作中心不能为空!");
        }
        if(dto.getTe011() == null || dto.getUdf51() == null || dto.getUdf52() == null || dto.getUdf53() == null) {
            throw new CustomException("500", "合格数量, 工废数量, 料废数量, 不良数量不能为空!");
        }
        if(dto.getTe011().add(dto.getUdf51()).add(dto.getUdf52()).add(dto.getUdf53()).compareTo(new BigDecimal(0)) <= 0) {
            throw new CustomException("500", "合格数量 + 工废数量 + 料废数量 + 不良数量需大于0!");
        }

        // 查询同一张派工单中，上一道工序的已报工数量。
//        SFCTA sfcta = sfctaMapper.getLastDishNum(dto.getTe006(), dto.getTe007(), dto.getTe008());
        // 查询MOCTY存不存在
        Mocty mocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getUuid()));
        if(mocty == null) {
            throw new CustomException("500", "排产数据不存在!");
        }
        if(!MOCStatusEnum.ShengChanZhong.getValue().equals(mocty.getUdf01().trim())) {
            throw new CustomException("500", "该单据未在" + MOCStatusEnum.ShengChanZhong.getValue() + "!");
        }

        // 查询本工序SFCTA
//        SFCTA bgxSfcta = sfctaMapper.selectOne(new LambdaQueryWrapper<SFCTA>().eq(SFCTA::getTA001, dto.getTe006()).eq(SFCTA::getTA002, dto.getTe007()).eq(SFCTA::getTA003, dto.getTe008()));
//        if(bgxSfcta == null) {
//            throw new CustomException("500",  dto.getTe006() + "-" + dto.getTe007() + ",工序" +  dto.getTe008() + "为空!");
//        }
        // 本工序已报数量
        BigDecimal bgNums = sfcteMapper.getAlreadyBGmocty(dto.getUuid(), dto.getTe008());

        SFCTD sfctd1 = new SFCTD();
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter yyyyMM = DateTimeFormatter.ofPattern("yyyyMMdd");
        sfctd1.setTD001("D410");
        Long dh = commonMapper.getDH2("SFCTD", "TD002", "TD001", "D410");
        if (dh == null) {
            dh = Long.parseLong(currentTime.format(yyyyMM)+"001");
        } else {
            dh++;
        }
        sfctd1.setTD002(""+dh);
        sfctd1.setTD003(nowTime.substring(0, 8));
        sfctd1.setTD004(dto.getTe024());
        sfctd1.setCREATE_DATE(nowTime);
        this.sfctdMapper.save(sfctd1);

        SFCTE sfcte = new SFCTE();
        sfcte.setTE001(sfctd1.getTD001());
        sfcte.setTE002(sfctd1.getTD002());
        sfcte.setTE003(SerialNumberSfcte(sfctd1.getTD001(), sfctd1.getTD002()));
        sfcte.setTE008(dto.getTe008());
        sfcte.setUDF09(dto.getUuid());    // MOCTY UUID
        sfcte.setUDF07(dto.getUdf07());
        sfcte.setTE004(dto.getTe004());
        sfcte.setTE009(dto.getTe009());

        //派工回写，工单工艺回写
        QueryWrapper<SFCTA> wrapper = new QueryWrapper<>();
        wrapper.eq("TA001", dto.getTe006())
                .eq("TA002", dto.getTe007())
                .eq("TA003", dto.getTe008());
        SFCTA sfcta1 = sfctaMapper.selectOne(wrapper);

        BigDecimal kebaoshu = moctyMapper.getKeBaoShu(mocty.getTy001(), mocty.getTy002());
        BigDecimal add = dto.getTe011().add(dto.getUdf51()).add(dto.getUdf52()).add(dto.getUdf53());
        if("ST4".equals(dto.getTe024().trim()) || "ST6".equals(dto.getTe024().trim())) {
            if(bgNums.add(add).compareTo(kebaoshu) > 0) {
                throw new CustomException("500", "报工单, 合格数量:" + dto.getTe011() + ", + 工废数量:" + dto.getUdf51() + ", + 料废数量:" + dto.getUdf52() + " , + 不良数量:" + dto.getUdf53() + " , + 已报工数量:" + bgNums + " 大于 " +
                        "总排产数量: " + kebaoshu + " !!");
            }
        }
        sfcte.setTE011(dto.getTe011());
        sfcte.setUDF51(dto.getUdf51());
        sfcte.setUDF52(dto.getUdf52());
        sfcte.setUDF53(dto.getUdf53());
        sfcte.setTE023(nowTime.substring(0, 8));
        sfcte.setTE024(dto.getTe024());          // 工作中心
        sfcte.setCREATOR(SecurityUtils.getLoginUser().getUsername());  // 报工提交账号
        sfcte.setCREATE_DATE(nowTime);
        sfcte.setTE017(dto.getTe017());
        sfcte.setTE018(dto.getTe018());
        sfcte.setTE019(dto.getTe019());
        sfcte.setTE020(dto.getTe020());
        sfcte.setTE006(dto.getTe006());
        sfcte.setTE007(dto.getTe007());

        sfcte.setTE021(dto.getTe021());
        this.sfcteMapper.insert(sfcte);

        if (sfcta1!=null) {
            SFCTA insertSfcta = new SFCTA();
            insertSfcta.setTA011(sfcta1.getTA011() == null ? dto.getTe011() : sfcta1.getTA011().add(dto.getTe011()));
            insertSfcta.setUDF51(sfcta1.getUDF51() == null ? dto.getUdf51() : sfcta1.getUDF51().add(dto.getUdf51()));
            insertSfcta.setUDF52(sfcta1.getUDF52() == null ? dto.getUdf52() : sfcta1.getUDF52().add(dto.getUdf52()));
            insertSfcta.setUDF53(sfcta1.getUDF53() == null ? dto.getUdf53() : sfcta1.getUDF53().add(dto.getUdf53()));
            sfctaMapper.update(insertSfcta, wrapper);
//            sfctaMapper.
        }
        com.example.entity.mysql.Resource one = resourceMapper.selectOne(new LambdaQueryWrapper<com.example.entity.mysql.Resource>()
                .eq(com.example.entity.mysql.Resource::getDeviceid, dto.getTe005()));
        if(one == null) {
            throw new CustomException("500", "机器编号: " + dto.getTe005() + "不存在!");
        }

        Mocty mocty33 = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getUuid()));
        String ty003 = mocty33.getTy003();
        List<Workresource> workresourceList = workresourceMapper.selectList
                (new LambdaQueryWrapper<Workresource>().eq(Workresource::getProductLineId, ty003));

        com.example.entity.mysql.Resource shebei = null;
        // 拿到设备
        for(Workresource t : workresourceList) {
            if(new Integer(1).equals(t.getResourceTypeId())) {
                shebei = resourceMapper.selectOne(
                        new LambdaQueryWrapper<com.example.entity.mysql.Resource>().
                                eq(com.example.entity.mysql.Resource::getResourceGroupIdIsF, t.getResourceId()));
                break;
            }
        }
        List<String> bydList = new ArrayList<>();
        String groupUuid = UUID.randomUUID().toString();
        for(Workresource t : workresourceList) {
            com.example.entity.mysql.Resource resource = resourceMapper.selectOne(
                    new LambdaQueryWrapper<com.example.entity.mysql.Resource>().
                            eq(com.example.entity.mysql.Resource::getResourceGroupIdIsF, t.getResourceId()));
            Resourceusehis resourceusehis = new Resourceusehis();
            resourceusehis.setResourcetype(resource.getResourceType());
            resourceusehis.setResourceid(resource.getResourceGroupIdIsF());
            resourceusehis.setResourceno(resource.getDeviceid());
            resourceusehis.setResourcename(resource.getDevicename());
            resourceusehis.setTy001(dto.getTe006());
            resourceusehis.setTy002(dto.getTe007());
            resourceusehis.setMoctyudf05(dto.getUuid());
            resourceusehis.setNum(add.doubleValue());
            resourceusehis.setGroupUuid(groupUuid);
            resourceusehis.setTE001(sfctd1.getTD001());
            resourceusehis.setTE002(sfctd1.getTD002());
            resourceusehis.setJinzhanUuid(resource.getJinzhanUuid());
            resourceusehis.setCreateTime(TimeUtils.getFullNowTime());
            resourceusehis.setDate(TimeUtils.HZStdTime());
            if(resource.getResourceType().equals(3)) {
                // 先找到工单  -》 再去productprocess找穴数。
                MOCTA mocta = moctaMapper.selectOne(new LambdaQueryWrapper<MOCTA>()
                        .eq(MOCTA::getTA001, dto.getTe006())
                        .eq(MOCTA::getTA002, dto.getTe007())
                );
                if (mocta==null) throw new CustomException("500","工单不存在");

                // 1. 取要把resourceType = 3 && jinzhanUuid = resource.getJinzhanUuid()  SUM(kai'he'mu)
                // 2. 取 这个工单之前已经报了多少了  resourceType = 3 && jinzhanUuid = resource.getJinzhanUuid()
                //获取同组工单目前开合情况
                List<Resourceusehis> resourceusehisList = resourceusehisService.lambdaQuery().eq(Resourceusehis::getResourcetype, 3)
                        .eq(Resourceusehis::getJinzhanUuid, resource.getJinzhanUuid())
                        .list();
                //同组工单在模具上的开合次数
                Double totalKaiHe = 0.0d;
                //当前工单已报工数量
                Double existsNum=0.0d;
                for (Resourceusehis i : resourceusehisList) {
                    if (i.getTy001().equals(dto.getTe006()) && i.getTy002().equals(dto.getTe007())) existsNum+=i.getNum();
                    i.setKaihemucishu(i.getKaihemucishu() == null ? 0.0d:i.getKaihemucishu());
                    totalKaiHe+=i.getKaihemucishu();
                }
                //获取模穴数量
                Productprocessresource prs = pprService.lambdaQuery().eq(Productprocessresource::getProductId, dto.getTe017())
                        .eq(Productprocessresource::getResourceTypeId, 3)
                        .eq(Productprocessresource::getInvrt_name, mocta.getUDF01())
                        .eq(Productprocessresource::getProcessRoute, mocta.getUDF02())
                        .eq(Productprocessresource::getProcessId, mocta.getUDF03()).one();
                //当前工单总报工数量对应开合次数
                double kaihe = Math.ceil((add.doubleValue() + existsNum) / prs.getUseCavityNumber());
                //得到需要增加的模具使用次数
                resourceusehis.setKaihemucishu(kaihe-totalKaiHe>0 ? kaihe-totalKaiHe:0);
                resourceusehisMapper.insert(resourceusehis);

                // 1.回写模具的resource的数量
                Double d = Double.parseDouble(resource.getUsedNumber()) + resourceusehis.getKaihemucishu();
                resource.setUsedNumber(d.toString());
                resourceMapper.update(resource, new LambdaQueryWrapper<com.example.entity.mysql.Resource>().eq(com.example.entity.mysql.Resource::getResourceGroupIdIsF, t.getResourceId()));
                // 2.看一下要不要触发自动生成保养单

                // TODO 2.1 查看之前绑定的模具是什么。如果是空，或者不是这个模具。则需要更新

                Sfcteresource sfcteresource = sfcteresourceMapper.selectOne(new LambdaQueryWrapper<Sfcteresource>().eq(Sfcteresource::getResourcegroupid, ""));
                if(sfcteresource == null) {
                    sfcteresource = new Sfcteresource();
                    sfcteresource.setUuid(UUID.randomUUID().toString());
                    sfcteresource.setStarttime(TimeUtils.getFullNowTime());
                    sfcteresource.setResourceid(resource.getResourceGroupIdIsF());
                    sfcteresource.setResourceno(resource.getDeviceid());
                    sfcteresource.setResourcename(resource.getDevicename());
                    sfcteresource.setResourcegroupid(shebei.getResourceGroupIdIsF());
                    sfcteresource.setResourcegroupno(shebei.getDeviceid());
                    sfcteresource.setResourcegroupname(shebei.getDevicename());
                    sfcteresourceMapper.insert(sfcteresource);
                }else{
                    if(!sfcteresource.getResourceid().equals(resource.getResourceGroupIdIsF())) {
                        // 先把之前的存到 历史表中
                        sfcteresource.setEndtime(TimeUtils.getFullNowTime());
                        Sfcteresourcehis his = new Sfcteresourcehis();
                        BeanUtils.copyPropertiesIgnoreCase(sfcteresource, his);
                        sfcteresourcehisMapper.insert(his);
                        sfcteresourceMapper.delete(new LambdaQueryWrapper<Sfcteresource>().eq(Sfcteresource::getUuid, sfcteresource.getUuid()));

                        sfcteresource = new Sfcteresource();
                        sfcteresource.setUuid(UUID.randomUUID().toString());
                        sfcteresource.setStarttime(TimeUtils.getFullNowTime());
                        sfcteresource.setResourceid(resource.getResourceGroupIdIsF());
                        sfcteresource.setResourceno(resource.getDeviceid());
                        sfcteresource.setResourcename(resource.getDevicename());
                        sfcteresource.setResourcegroupid(shebei.getResourceGroupIdIsF());
                        sfcteresource.setResourcegroupno(shebei.getDeviceid());
                        sfcteresource.setResourcegroupname(shebei.getDevicename());
                        sfcteresourceMapper.insert(sfcteresource);
                    }
                }

                // 拿到UUID，然后去EQTTE2中找，如果EQTTE2中有UDF01 和 UDF02是这个模具的，说明已经生成过了。
                // 1. 宏竹的模具保养单，先写死。
                // 先查出来要触发哪几个  排序过的
                List<Maintainplan> mpList = maintainplanMapper.mouldOnList();
                int usedNum = d.intValue();// 模具已使用次数
                int hours = (int) TimeUtils.getDifferenceInHours(sfcteresource.getStarttime(), TimeUtils.getFullNowTime()); // 改模具已使用的小时数
                // eqtteMapper.selectList(new LambdaQueryWrapper<Eqtte>().eq(Eqtte::getUDF01, sfcteresource.getUuid()));
                Eqtte before = eqtteMapper.getEqtteBySfcteResourceUuid(sfcteresource.getUuid() == null ? "fdsagdsagdasgs" : sfcteresource.getUuid());
                Maintainplan needToUse = null;   // 需要去生成的项目
                if(before == null) {  // 如果之前没有的话，从第一层往下走。看看最多能达到第几层。 只要最后一层
                    for(Maintainplan mp : mpList) {
                        // 找出每个项目的规则
                        Maintainplanrule rule = maintainplanruleMapper.selOnRuleByMpuuid(mp.getMpuuid());
                        boolean ok = isOk(usedNum, hours, rule);
                        if(ok == true) {
                            needToUse = mp;
                        }else{
                            break;
                        }
                    }
                }else{  // 如果之前有最新的话，就一级一级往下走。
                    // 找到他的下一个，然后看看是否有达到项目要求
                    Maintainplan next = maintainplanMapper.getNextMaintainPlan(before.getTE029());
                    if(next != null) {
                        Maintainplanrule rule = maintainplanruleMapper.selOnRuleByMpuuid(next.getMpuuid());
                       if(rule != null && isOk(usedNum, hours, rule)) {  // 如果达到要求，就直接去生成
                           needToUse = next;
                       }
                    }
                }
                System.out.println("needToUse = " + needToUse);

//                for(Maintainplan plan : mpList) {
//                    // 找到开启的规则。  找到数量最小的
//                    Maintainplanrule rule = maintainplanruleMapper.selMinNum(plan.getMpuuid());
//                    if(rule == null) continue;
//                    //
//                    ResourceMaintainplan selected = resourceMaintainplanMapper.selectOne(new LambdaQueryWrapper<ResourceMaintainplan>()
//                            .eq(ResourceMaintainplan::getMpuuid, plan.getMpuuid())
//                            .eq(ResourceMaintainplan::getResourceno, resource.getDeviceid()));
//                    // 插入新数据
//                    ResourceMaintainplan x = new ResourceMaintainplan();
//                    x.setMpuuid(plan.getMpuuid());
//                    x.setResourcetype(3);
//                    x.setResourceid(resource.getResourceGroupIdIsF());
//                    x.setResourceno(resource.getDeviceid());
//                    x.setResourcename(resource.getDevicename());
//                    x.setLastnum(Double.parseDouble(resource.getUsedNumber()));
//                    if(selected == null) resourceMaintainplanMapper.insert(x);
//                    else resourceMaintainplanMapper.update(x, new LambdaQueryWrapper<ResourceMaintainplan>()
//                            .eq(ResourceMaintainplan::getMpuuid, plan.getMpuuid())
//                            .eq(ResourceMaintainplan::getResourceno, resource.getDeviceid()));
//                    // 生成保养单
//                    Eqtte eqtte = new Eqtte();
//                    eqtte.setTE001("BYD");
//                    eqtte.setTE002(eqtteMapper.selTe002(eqtte.getTE001()));
//                    eqtte.setTE003(TimeUtils.HZStdTime());
//                    eqtte.setTE004("1");
//                    eqtte.setTE008("3");
//                    eqtte.setTE010(resource.getResourceGroupIdIsF().toString());
//                    eqtte.setTE011(resource.getDeviceid());
//                    eqtte.setTE012(resource.getDevicename());
//                    eqtte.setTE019("0");
//                    eqtte.setTE027("自动生成");
//                    eqtte.setTE028(plan.getMpuuid().toString());  // 计划UUID
//                    eqtte.setTE029(plan.getMpid());  // 计划编号
//                    eqtte.setTE030(plan.getMpname());  // 计划名称
//                    eqtte.setTE031(TimeUtils.HZStdTime());
//                    eqtte.setTE032(TimeUtils.HZStdTime());
//                    eqtte.setTE059(one.getResourceGroupIdIsF().toString());
//                    eqtte.setTE060(one.getDeviceid());
//                    eqtte.setTE061(one.getDevicename());
//                    eqtte.setCREATE_DATE(TimeUtils.getFullNowTime());
//                    eqtte.setCREATOR("ERP");
//                    eqtteMapper.insert(eqtte);
//                    // 获取单身的项目 通过planitem
//                    List<Maintainplanitem> itemList = maintainplanitemMapper.selListByMpuuid(plan.getMpuuid());
//                    int idx = 1;
//                    for(Maintainplanitem item : itemList) {
//                        Eqttf eqttf = new Eqttf();
//                        eqttf.setTF001(eqtte.getTE001());
//                        eqttf.setTF002(eqtte.getTE002());
//                        eqttf.setTF003(""+idx);  idx++;
//                        eqttf.setUDF01(item.getMpiid());  // 维护编号
//                        eqttf.setUDF02(item.getMpiname());  // 维护名称
//                        eqttf.setTF005(item.getMpicontent());  // 维护内容
//                        eqttf.setTF008(item.getMpiresulttype());  // 结果类型 1.文字 2.数值 3.日期[DEF:1]
//                        eqttf.setCREATE_DATE(TimeUtils.getNowTime());
//                        eqttf.setCREATOR("ERP");
//                        eqttfMapper.insert(eqttf);
//                    }
//                    bydList.add(eqtte.getTE002());
//                }
            }else if(resource.getResourceType().equals(1)) {
                resourceusehisMapper.insert(resourceusehis);
            }else{  // 如果是2，4的话
                resourceusehisMapper.insert(resourceusehis);
            }
        }

//        for(String s : bydList) {
//            // 消息通知
//            znxService.saveZnxAndSendMessage(MessageTypeEnum.BAOYANG.getValue(),
//                    "有一张保养单待处理, 单号：" + s, ZnxStatusEnum.DAIBAN.getValue());
//        }

        return Result.success();
    }

    /**
     *
     * @param usedNums 已使用的开合模次数
     * @param usedHours 已使用的小时数
     * @param rule 规则类
     * @return
     */
    private boolean isOk(int usedNums, int usedHours, Maintainplanrule rule) {
        String assoSymbol = "";
        if(com.example.untils.StringUtils.isEmpty(rule.getAssociatedSymbol())) {
            assoSymbol = "OR";
        }else{
            assoSymbol = rule.getAssociatedSymbol();
        }
        if("OR".equals(assoSymbol)) {
            if(com.example.untils.StringUtils.isNotEmpty(rule.getMprUntimeDaysSymbol())
                    && rule.getMpruntimedays() != null) {
                int value = rule.getMpruntimedays().intValue();
                if("<".equals(rule.getMprUntimeDaysSymbol())) {
                    if(usedHours < value * 24) {
                        return true;
                    }
                    return false;
                }else if(">=".equals(rule.getMprUntimeDaysSymbol())) {
                    if(usedHours >= value * 24) {
                        return true;
                    }
                    return false;
                }else{
                    return false;
                }
            }

            if(com.example.untils.StringUtils.isNotEmpty(rule.getMprUntimeValueSymbol())
                    && rule.getMpruntimevalue() != null) {
                int value = rule.getMpruntimevalue().intValue();
                if("<".equals(rule.getMprUntimeValueSymbol())) {
                    if(usedNums < value) {
                        return true;
                    }
                    return false;
                }else if(">=".equals(rule.getMprUntimeValueSymbol())) {
                    if(usedNums >= value) {
                        return true;
                    }
                    return false;
                }else return false;
            }
            return false;
        }else{  // "AND"
            if(com.example.untils.StringUtils.isNotEmpty(rule.getMprUntimeDaysSymbol())
                    && rule.getMpruntimedays() != null) {
                int value = rule.getMpruntimedays().intValue();
                if("<".equals(rule.getMprUntimeDaysSymbol())) {
                    if(!(usedHours < value * 24)) {
                        return false;
                    }
                }else if(">=".equals(rule.getMprUntimeDaysSymbol())) {
                    if(!(usedHours >= value * 24)) {
                        return false;
                    }
                }else return false;
            }else{
                return false;
            }

            if(com.example.untils.StringUtils.isNotEmpty(rule.getMprUntimeValueSymbol())
                    && rule.getMpruntimevalue() != null) {
                int value = rule.getMpruntimevalue().intValue();
                if("<".equals(rule.getMprUntimeValueSymbol())) {
                    if(usedNums < value) {
                        return true;
                    }
                    return false;
                }else if(">=".equals(rule.getMprUntimeValueSymbol())) {
                    if(usedNums >= value) {
                        return true;
                    }
                    return false;
                }else return false;
            }else{
                return false;
            }
        }
    }

}
